import { fetchRoleList, RolesApi } from '@/api/userCenter/authority/roles'
import { useStore } from '@/store'
import { computed, reactive } from 'vue'
import { TableStateWrapper } from '../types'
import { FormProps, FormItemOption } from '@/components/Form/types'
import {
  GetRoleListReq,
  RoleItem,
} from '@/api/userCenter/authority/model/roleModel'
import { formatPagination } from '@/utils/antdOpFormatHelper'

const useSearchRole = () => {
  const store = useStore()
  /**
   * 表格相关状态
   */
  const tableStateWrapper = reactive<TableStateWrapper>({
    selectedRowKeys: [],
    tableData: [],
    tableSize: 'small',
    pageInfo: {
      pageSize: 10,
      current: 1,
      total: 0,
    },
    tableColumns: [
      {
        title: 'ID',
        dataIndex: 'id',
      },
      {
        title: '角色名称',
        dataIndex: 'name',
      },
      {
        title: '所属应用',
        dataIndex: 'permName',
      },
      {
        title: '权限标识',
        dataIndex: 'code',
      },
      {
        title: '备注',
        dataIndex: 'note',
      },
      {
        title: '操作',
        dataIndex: 'options',
        width: 50,
        slots: {
          customRender: 'options',
        },
      },
    ],
  })
  /**
   * 查询表单相关状态
   */
  const queryFormState = reactive({
    roleName: '',
  })
  /**
   * 表单绑定属性
   */
  const queryFormBind: FormProps = {
    model: queryFormState,
  }
  /**
   * 表单生成配置
   */
  const queryFormList: FormItemOption[] = [
    {
      formProps: {
        label: '角色名称',
        name: 'roleName',
      },
      inputOption: {
        tag: 'a-input',
        props: {
          placeholder: '输入角色名称',
        },
      },
    },
  ]

  /**
   * 获取角色列表
   */
  const getRoleList = async () => {
    if (!tableStateWrapper.pageInfo) return
    const reqData: GetRoleListReq = {
      key: queryFormState.roleName,
      current: tableStateWrapper.pageInfo.current,
      size: tableStateWrapper.pageInfo.pageSize,
    }
    const { data } = await fetchRoleList(reqData)
    tableStateWrapper.tableData = data.records
    tableStateWrapper.pageInfo = formatPagination(data)
    tableStateWrapper.selectedRowKeys = []
  }
  const isGetRoleListLoading = computed(() =>
    store.getters['global/isOpLoading'](RolesApi.GET_ROLE_LIST)
  )

  const rowSelection = {
    onChange: (selectedRowKeys: string[], selectedRows: RoleItem[]) => {
      console.log(
        'selectedRowKeys:',
        selectedRowKeys,
        'selectedRows: ',
        selectedRows
      )
      tableStateWrapper.selectedRowKeys = selectedRowKeys
    },
  }

  return {
    tableStateWrapper,
    getRoleList,
    isGetRoleListLoading,
    queryFormBind,
    queryFormList,
    rowSelection,
  }
}

export default useSearchRole
